package com.objectoriented.tang.controller;

import com.objectoriented.tang.DBpojo.User;
import com.objectoriented.tang.pojo.CheckBoard;
import com.objectoriented.tang.service.UserService;
import com.objectoriented.tang.utils.chessboardUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RestController;

import javax.faces.event.WebsocketEvent;
import javax.faces.event.WebsocketEvent.Closed;
import javax.websocket.OnClose;
import java.rmi.server.UID;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@RestController
public class WebSocketController {
    @Autowired(required = false)
    private SimpMessagingTemplate template;
    @Autowired(required = false)
    private UserService userService;
    private static HashMap<String, CheckBoard> chessboardMap=new HashMap<String,CheckBoard>();

    @MessageMapping("/chessboard")
    public void chessboard(Map<String,Object> data) {
        //发送消息给指定用户
        int x=(int)data.get("x");
        int y=(int)data.get("y");
        int RID=(int)data.get("RID");
        int ownUID=(int) data.get("ownUID");
        int enemyUID=(int)data.get("enemyUID");
        String startTime=(String)data.get("startTime");
        String endTime=(String)data.get("endTime");
        HashMap<String,Object> returnMap=new HashMap<String, Object>();
        returnMap.put("x",x);
        returnMap.put("y",y);
        returnMap.put("chessOwnerUID",ownUID);


        //如果是新开局，就创建新棋盘
        CheckBoard checkBoard=null;
        if (chessboardMap.get(RID+"")==null){
            System.out.println(ownUID+"新开了一盘棋");
            checkBoard=new CheckBoard();
            chessboardMap.put(RID+"",checkBoard);
        }else {
            checkBoard=chessboardMap.get(RID+"");
        }

        System.out.println(ownUID+"下的棋子："+x+","+y);
        //如果当前棋子赢了，保存胜局进数据库，清空棋盘，发送胜利信号给胜者
        if (checkBoard.isWin(x,y,ownUID)){
            System.out.println(ownUID+"获胜了");

            HashMap<String,Object> DBmap= new HashMap<String,Object>();
            if (startTime!=null&&endTime!=null){
                DBmap.put("startTime",startTime);
                DBmap.put("endTime",endTime);
            }
            DBmap.put("user_A_UID",ownUID);
            DBmap.put("user_B_UID",enemyUID);
            DBmap.put("winner",ownUID);
            userService.addHistory(DBmap);

            //更新隐藏分
            HashMap<String,Object> updateMap= new HashMap<String,Object>();
            updateMap.put("UID",ownUID);
            User ownUser = userService.getUser(updateMap);
            updateMap.put("key","hidden_Point");
            updateMap.put("value",ownUser.getHidden_Point()+1);
            userService.update(updateMap);//胜者隐藏分+1
            updateMap.put("key","winNumber");
            updateMap.put("value",ownUser.getWinNumber()+1);
            userService.update(updateMap);//胜者胜场+1

            updateMap.put("UID",enemyUID);
            User enemyUser = userService.getUser(updateMap);
            updateMap.put("key","hidden_Point");
            updateMap.put("value",enemyUser.getHidden_Point()-1);
            userService.update(updateMap);//败者隐藏分-1
            updateMap.put("key","loseNumber");
            updateMap.put("value",enemyUser.getLoseNumber()+1);
            userService.update(updateMap);//败者负场+1

            returnMap.put("status",0);//状态为0，有人赢了
            chessboardMap.remove(RID+"");//移除棋盘
        }else {
            checkBoard.addChess(x,y,ownUID);
            returnMap.put("status",1);//状态为1，游戏继续
        }
        //发送棋盘信息给和自己对手
        template.convertAndSend("/user/chessboard/"+ownUID,returnMap );
        template.convertAndSend("/user/chessboard/"+enemyUID,returnMap );
    }

    @MessageMapping("/chat")//发送消息给指定用户
    public void chat(Map<String,Object> data) {
        String content=(String)data.get("content");
        int ownUID=(int)data.get("ownUID");
        int enemyUID=(int)data.get("enemyUID");
        System.out.println(content+ownUID+enemyUID);
        System.out.println("--------------------------------------------------------------");
        HashMap<String,Object> returnMap=new HashMap<String, Object>();

        returnMap.put("content",content);
        returnMap.put("enemyUID",ownUID);
        template.convertAndSend("/user/chat/"+enemyUID,returnMap );
    }

    // 认输（1）、求和（2）、同意认输（3）、
    // 拒绝认输（4）、同意求和（5）、拒绝求和（6）
    // 请求悔棋（7）、同意悔棋（8）、拒绝悔棋（9）
    @MessageMapping("/operation") //发送操作码给指定用户
    public void operation(Map<String,Object> data) {

        int operation=(int)data.get("operation");
        int RID=(int)data.get("RID");
        int ownUID=(int)data.get("ownUID");
        int enemyUID=(int)data.get("enemyUID");

        String startTime=(String)data.get("startTime");
        String endTime=(String)data.get("endTime");
        HashMap<String,Object> returnMap=new HashMap<String, Object>();

        //如果同意悔棋，那么棋盘的棋子位置变为空
        if (operation==8){
            int x=(int)data.get("x");
            int y=(int)data.get("y");
            CheckBoard checkBoard=chessboardMap.get(RID+"");
            checkBoard.addChess(x,y,0);
            returnMap.put("x",x);
            returnMap.put("y",y);
        }

        if (operation==3||operation==5){
            HashMap<String,Object> DBmap= new HashMap<String,Object>();
            if (startTime!=null&&endTime!=null){
                DBmap.put("startTime",startTime);
                DBmap.put("endTime",endTime);
            }
            DBmap.put("user_A_UID",ownUID);
            DBmap.put("user_B_UID",enemyUID);
            DBmap.put("winner",ownUID);
            userService.addHistory(DBmap);

            //更新隐藏分
            //胜者隐藏分+1
            HashMap<String,Object> updateMap= new HashMap<String,Object>();
            updateMap.put("UID",ownUID);
            User ownUser = userService.getUser(updateMap);
            updateMap.put("key","hidden_Point");
            updateMap.put("value",ownUser.getHidden_Point()+1);
            userService.update(updateMap);
            //败者隐藏分-1
            updateMap.put("UID",enemyUID);
            User enemyUser = userService.getUser(updateMap);
            updateMap.put("key","hidden_Point");
            updateMap.put("value",enemyUser.getHidden_Point()-1);
            System.out.println(userService.update(updateMap)+"隐藏分改变！");

            chessboardMap.remove(RID+"");//移除棋盘
        }

        returnMap.put("result",operation);
        returnMap.put("enemyUID",ownUID);
        returnMap.put("RID",RID);

        template.convertAndSend("/user/operation/"+enemyUID,returnMap );
    }

    @MessageMapping("/close") //关闭网页请求
    public void onClose(Map<String,Object> data){
        int RID=(int)data.get("RID");
        int ownUID=(int) data.get("ownUID");
        int enemyUID=(int)data.get("enemyUID");
        System.out.println("有一连接关闭！UID为" + ownUID);

        chessboardMap.remove(RID+"");//移除棋盘
        HashMap<String,Object> returnMap=new HashMap<String, Object>();
        returnMap.put("status",1);//收到1代表你的对手已经下线
        template.convertAndSend("/user/close/"+enemyUID,returnMap );
    }
}